/**
 * 大转盘抽奖
 */
// var util = require("../../utils/util.js");
var app = getApp(), fetchApi = require("../../../utils/httpPost.js");
import Toast from '../../../component/vant/toast/toast';
Page({
  //奖品配置
  awardsConfig: {
    chance: true,
  },
  data: {
    loading: false,
    netWork: true,
    isLoading: true,
    awardsList: {},
    animationData: {},
    btnDisabled: '',
    activity: [],
    is_has_activity: 0,
    is_open_activity:0,
    autoplay:true,
    winner_records:[],
    roles:[],
    awards: [
      // { 'index': 0, 'raffleGoodsName': '敬请期待' },
      // { 'index': 1, 'raffleGoodsName': '敬请期待' },
      // { 'index': 2, 'raffleGoodsName': '敬请期待' },
      // { 'index': 3, 'raffleGoodsName': '敬请期待' },
      // { 'index': 4, 'raffleGoodsName': '敬请期待' },
    ],
    lottery_count:0,
    max_draw_count:0,
    share_count:0,
    submitState:false,
    ag_id:0,
    isLogin:0,
    goods_count:5,
    open_title:'',
  },
  onLoad(options){
    if(options.ag_id){
      this.data.ag_id = parseInt(options.ag_id);
    }
    console.log('onLoad this.data.ag_id',this.data.ag_id)
  },
  onShow: function (e) {
    var user_id = app.getStorageSync('user_id')
    console.log('onShow user_id',user_id)
    if (user_id > 0){
      this.onHttpInit();
    } else {
      if(this.data.ag_id > 0){
        wx.navigateTo({
          url: '/pages/login/index?ag_id=' + this.data.ag_id + '&from_type=raffle',
        })
      }else{
        wx.navigateTo({
          url: '/pages/login/index',
        })
      }
    }
  },
  loginOp: function () {
    var that = this
    // 登录
    wx.login({
      success: res => {
        console.log("code", res.code)
        fetchApi.httpPost('/user/wxLogin', { code: res.code }, function (res) {
          console.log("登录返回数据", res)
          app.globalData.user_id = res.data.data.user_id
          app.setStorageSync("user_id", res.data.data.user_id);
          app.setStorageSync("is_mer", res.data.data.is_mer);
          app.setStorageSync("shop_id", res.data.data.shop_id);
          app.setStorageSync("is_admin", res.data.data.is_admin);
          console.log("登录返回数据11", res)
          that.onHttpInit()
            that.setData({ is_mer: res.data.data.is_mer == 1 ? true : false })
            wx.getUserInfo({
              success: function (res_user) {
                app.globalData.userInfo = res_user.userInfo
                fetchApi.httpPost('/user/getUserInfo', {
                  iv: res_user.iv,
                  encryptedData: res_user.encryptedData,
                  rawData: res_user.rawData
                }, function (res_info) {

                }, function () { })
                // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                // 所以此处加入 callback 以防止这种情况
                if (that.userInfoReadyCallback) {
                  that.userInfoReadyCallback(res_user)
                }
              }
            })
        }, function () { })
      }
    })
  },
  onHttpInit: function () {
    var that = this
    fetchApi.httpPost('/raffle/lotteryInfoNew', {}, function (res) {
      console.log("获取抽奖活动数据", res)
      if (res.data.code == 0) {
        if(res.data.data.is_has_activity == 1){
          that.data.awards = res.data.data.goods;
        }
        that.data.lottery_count = res.data.data.lottery_count;
        that.data.activity = res.data.data.is_has_activity == 1 ? res.data.data.activity : [];
        that.setData({
          is_has_activity: res.data.data.is_has_activity,
          hasData: true,
          awards: res.data.data.is_has_activity == 1 ? res.data.data.goods : that.data.awards,
          winner_records: res.data.data.records,
          roles: res.data.data.activity !=undefined ? res.data.data.activity.roleInfos : {},
          activity: res.data.data.is_has_activity == 1 ? res.data.data.activity : [],
          lottery_count: res.data.data.lottery_count ? res.data.data.lottery_count:0,
          share_count: res.data.data.share_count ? res.data.data.share_count : 0,
          max_draw_count: res.data.data.max_draw_count ? res.data.data.max_draw_count : 0,
          is_open_activity: res.data.data.is_open_activity ? res.data.data.is_open_activity : 0,
          goods_count: res.data.data.goods_count ? res.data.data.goods_count : 4,
          open_title: res.data.data.open_title ? res.data.data.open_title : "",
        })
        // if(res.data.data.is_has_activity == 1){
        // }
        that.drawAwardRoundel();
        wx.setNavigationBarTitle({
          title: res.data.data.is_has_activity == 1 ? res.data.data.activity.raffleTitle : '抽奖活动'//页面标题为路由参数
        })
      }
      that.setData({ netWork: true, loading: true,isLoading: false, })
    }, function () {
      that.setData({ netWork: false, loading: true, isLoading: false, })
    })
  },
  //画抽奖圆盘
  drawAwardRoundel: function () {
    var awards = this.data.awards;
    console.log('awards',awards)
    var awardsList = [];
    // 文字旋转 turn 值
    var turnNum = 1 / awards.length; 
    // 奖项列表
    for (var i = 0; i < awards.length; i++) {
      awardsList.push({ 
        turn: i * turnNum + 'turn',
        lineTurn: i * turnNum + turnNum / 2 + 'turn', 
        award: awards[i].goodsNameArray ,
        title: awards[i].raffleTitle
      });
    }
    this.setData({
      btnDisabled: this.awardsConfig.chance ? '' : 'disabled',
      awardsList: awardsList
    });
  },
  //发起抽奖
  playReward: function () {
    if(this.data.is_has_activity == 1){
      this.onHttpPlayReward();
    }else{
      Toast("抽奖活动未开启");
    }
  },
  onHttpPlayReward: function () {
    console.log('this.data.btnDisabled',this.data.btnDisabled);
    if(this.data.btnDisabled != ''){
      console.log('不要点太快哟');
      Toast("不要点太快哟~")
      return;
    }
    this.data.btnDisabled = 'disabled';
    this.setData({
      btnDisabled: 'disabled'
    });

    var that = this;
    fetchApi.httpPost('/raffle/lottery', {
      
    }, function (res) {
      console.log("抽奖结果", res)
      if (res.data.code == 0) {
        //中奖index
        var awardIndex = res.data.data.index;
        var runNum = 6;//旋转8周
        var duration = 4000;//时长
        // 旋转角度
        that.runDeg = that.runDeg || 0;
        that.runDeg = that.runDeg + (360 - that.runDeg % 360) + (360 * runNum - awardIndex * (360 / that.data.awards.length))
        //创建动画
        var animationRun = wx.createAnimation({
          duration: duration,
          timingFunction: 'ease'
        })
        animationRun.rotate(that.runDeg).step();
        that.setData({
          animationData: animationRun.export(),
        });

        var lottery_count = that.data.lottery_count
        if (lottery_count > 0){
          that.setData({ lottery_count: lottery_count - 1})
        }

        // 中奖提示
        setTimeout(function () {
          wx.showModal({
            title: '抽奖结果',
            content: res.data.msg,
            showCancel: false
          });
          that.data.btnDisabled = '';
          that.setData({
            btnDisabled: ''
          });
        }.bind(that), duration);
      } else {
        Toast.fail(res.data.msg);
      }
      that.setData({ netWork: true, isLoading: false, })
    }, function () {
      that.setData({ netWork: false, hasData: false, isLoading: false, })
    })
  },
  onShareAppMessage: function (options) {
    var that = this;
    var user_id = app.getStorageSync("user_id");
    return {
      title: '抽奖活动',
      path: '/pagesFarm/pages/raffle/index?ag_id='+user_id , // 相对的路径
      success: (res) => {    // 成功后要做的事情
        console.log('分享成功', res)
      },
      complete: function (res) {
      },
      fail: function (res) {
        // 分享失败
        console.log('分享失败',res)
      }
    }
  },
  showRole:function(){
    wx.navigateTo({ url : '/pages/activityinfo/index' })
  },
  goHome:function(){
    wx.switchTab({ url: '/pages/home/home' })
  }
})
